{% extends "base.html" %}
{% load staticfiles %}
{% block titile %}行情信息{% endblock %}
{% block content %}
    <!-- 先引入 Vue -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jsrender/0.9.91/jsrender.min.js" charset="utf-8"></script>
    <script src="https://cdn.bootcss.com/vue/2.5.13/vue.min.js"></script>
    <script src="https://cdn.bootcss.com/axios/0.17.1/axios.min.js"></script>
    <!-- 引入组件库 -->
    <script src="https://cdn.bootcss.com/element-ui/2.1.0/index.js"></script>
    <div id="dataapp" style="width: 100%;height: 600px">
        {#        <el-dialog  title="请登录" :visible.sync="LoginFormVisible" :close-on-click-modal="false" :show-close ="false" :lock-scroll="true">#}
        {#                <el-form :model="loginForm">#}
        {##}
        {#                        <el-input type="text" v-model="loginForm.user" value="{{ username1 }}" auto-complete="off"></el-input>#}
        {##}
        {##}
        {##}
        {#                        <el-input type="password" v-model="loginForm.pwd" value="{{ password1 }}" auto-complete="off"></el-input>#}
        {##}
        {#                </el-form>#}
        {#                <div slot="footer" class="dialog-footer">#}
        {#                    <el-button type="primary" @click="onLogin">确 定</el-button>#}
        {#                </div>#}
        {#            </el-dialog>#}
        <button type="button" @click="gContract" style="width: 8%;height: 32px;margin-left: 12px">获取数据</button>
        <button type="button" @click="gGateway" style="width: 8%;height: 32px;margin-left: 12px">连接CTP</button>
        {#    <el-input style="width: 100%;height: 100px" type="hidden" v-model="loginForm.user" auto-complete="off"></el-input>#}
        <el-table :data="contract" stripe :height="window.innerHeight" style="width: 100%">
            <el-table-column prop="symbol" label="合约代码"></el-table-column>
            <el-table-column prop="exchange" label="交易所"></el-table-column>
            <el-table-column prop="vtSymbol" label="vt系统代码"></el-table-column>
            <el-table-column prop="name" label="日期"></el-table-column>
            <el-table-column prop="productClass" label="合约类型"></el-table-column>
            <el-table-column prop="size" label="大小"></el-table-column>
            <el-table-column prop="priceTick" label="最小价格变动"></el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
                <template slot-scope="scope">
                    <el-button @click="handleClick(scope.row)" type="text" size="small">订阅</el-button>
                </template>
            </el-table-column>
        </el-table>
        {#        <table width="100%":data="{% static 'data/contract.json'%}" style="height: 600px">#}
        {#            <table-column prop="vtSymbol" label="合约代码"></table-column>#}
        {#            <table-column prop="symbol" label="交易所"></table-column>#}
        {#            <table-column prop="vtSymbol" label="Vt系统代码"></table-column>#}
        {#            <table-column prop="name" label="日期"></table-column>#}
        {#            <table-column prop="productClass" label="合约类型"></table-column>#}
        {#            <table-column prop="size" label="大小"></table-column>#}
        {#            <table-column prop="priceTick" label="最小价格变动"></table-column>#}
        {#            <table-column prop="address" label="操作"></table-column>#}
        {#        </table>#}
    </div>
    <script>
        var host = window.location;
        var _strategy = new Object()
        new Vue({
            el: '#dataapp',
            data: function () {
                return {
                    table_height: 600 + 'px',
                    winHeight: window.innerHeight,
                    topFrame: window.innerHeight * 2 / 3 - 65 + "px",
                    bottomFrame: window.innerHeight / 3 - 65 + "px",
                    leftTradeHeight: (window.innerHeight - 50) + 'px',
                    selected_data: [],
                    form: {
                        volume: 1,
                        vtSymbol: '',
                        lastPrice: '',
                        direction: '',
                        offset: '',
                        priceType: '',
                    },
                    loginForm: {
                        user: "",
                        pwd: ""
                    },
                    LoginFormVisible: true,
                    formLabelWidth: '120px',
                    eAccount: [],
                    eTick: [],
                    tickObj: {},
                    eContract: [],
                    connection: '未连接',
                    activeTab: "home",
                    activeTabLeft: 'trade',
                    activeTabRight: 'position',
                    log: [], //日志
                    position: [], //持仓
                    order: [], //委托
                    orderObj: {}, //委托对象
                    trade: [], //成交
                    account: [], //资金
                    error: [], //错误
                    contract: [], //合约查询结果
                    leftTrade: {}, //存放左侧交易区显示数据
                    config: {}, //存放token等数据
                    strategy: {}, //策略名
                    ctaLog: [],
                    loading: {
                        subScribe: false,
                        order: false,
                        contract: false,
                        strategy: false,
                        token: false,
                    },
                }
            },
            created: function () {
                this.gAccount()
                this.gConnectionStatus()
                this.gTick()
                this.gLog()
                this.gPosition()
                this.gError()
                this.gOrder()
                this.gTrade()

            },
            methods: {

                onLogin() {
                    console.log(this.loginForm.user)
                    let userName = this.loginForm.user,
                        pwd = this.loginForm.pwd;
                    this.gToken(userName, pwd)
                },
                gToken(username, password) {
                    const that = this;
                    that.loading.token = true;
                    axios.get(host + '/token?username=' + username + '&password=' + password)
                        .then(function (res) {
                            that.loading.token = false;
                            if (res.status == 200 && res.data.result_code == "success") {
                                that.$message({message: '已登录', type: 'success'});
                                that.config.token = res.data.data
                                that.LoginFormVisible = false
                                that.onLoadInfo('account', 'account')
                                that.onLoadInfo('trades', 'trade')
                                that.onLoadInfo('position', 'position')
                                that.onLoadInfo('order', 'order')
                                that.onLoadInfo('log', 'log')
                                that.onLoadInfo('error', 'error')
                            } else {
                                that.$notify({
                                    title: '警告',
                                    message: 'token获取失败，用户名或密码错误',
                                    type: 'warning',
                                    duration: 0,
                                });
                            }
                        })
                        .catch(function (err) {
                            that.loading.token = false;
                            that.$notify({title: '警告', message: 'token获取失败，连接错误', type: 'warning', duration: 0,});
                        });
                },

                doAction(e, type) {

                    if (this.config.token == undefined || this.config.token == "") {
                        this.$alert('请先登录', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    if (this.config.gateway == undefined || this.config.gateway == "") {
                        this.$alert('请先连接CTP', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    let name = e,
                        that = this,
                        info = "";
                    switch (type) {
                        case "init":
                            info = "初始化"
                            break;
                        case "stop":
                            info = "停止"
                            break;
                        case "start":
                            info = "启动"
                            break;
                    }

                    axios.post(host + "/ctastrategy/" + type, {
                        name: name,
                        token: this.config.token
                    })
                        .then(res => {
                            if (res.data.result_code == "success") {
                                that.$message({message: name + info + '成功', type: 'success'});
                                if (type == "start") {
                                    that.gCtaStrategy()
                                }
                            } else {
                                that.$message({message: name + info + '成功', type: 'fail'});
                            }
                        })
                        .catch(res => {
                            that.$message({message: name + info + '成功', type: 'fail'});
                        })
                },
                doOnLoad() {

                    if (this.config.token == undefined || this.config.token == "") {
                        this.$alert('请先登录', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    if (this.config.gateway == undefined || this.config.gateway == "") {
                        this.$alert('请先连接CTP', '警告', {confirmButtonText: '确定',});
                        return;
                    }


                    const that = this;
                    let strategy = {};
                    that.loading.strategy = true;
                    axios.post(host + '/ctastrategy/load', {
                        token: this.config.token
                    })
                        .then(res => {
                            if (res.data.result_code !== "success") {
                                that.$notify({
                                    title: '警告',
                                    message: 'ctastrategy/load接口报错',
                                    type: 'warning',
                                    duration: 0,
                                });
                                return;
                            } else {
                                let strategy = res.data.data;
                                strategy.forEach((item) => {
                                    _strategy[item] = {name: item};
                                    that.gParams(item)
                                    that.gVar(item)
                                })
                            }
                        })
                },
                gVar(name) {

                    if (this.config.token == undefined || this.config.token == "") {
                        this.$alert('请先登录', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    if (this.config.gateway == undefined || this.config.gateway == "") {
                        this.$alert('请先连接CTP', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    const that = this,
                        _var = new Object();
                    axios.get(host + "/ctastrategy/var?name=" + name + "&token=" + this.config.token)
                        .then(res => {
                            if (res.data.result_code !== "success") {
                                that.$notify({
                                    title: '警告',
                                    message: 'ctastrategy/var接口报错',
                                    type: 'warning',
                                    duration: 0,
                                });
                                return;
                            } else {
                                _strategy[name]['var'] = res.data.data;
                                that.strategy = _strategy;
                                that.loading.strategy = false;
                            }
                        })
                        .catch(res => {
                            that.$notify({title: '警告', message: 'ctastrategy/var接口报错', type: 'warning', duration: 0,});
                        })
                },
                gParams(name) {

                    if (this.config.token == undefined || this.config.token == "") {
                        this.$alert('请先登录', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    if (this.config.gateway == undefined || this.config.gateway == "") {
                        this.$alert('请先连接CTP', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    const that = this;
                    axios.get(host + "/ctastrategy/param?name=" + name + "&token=" + this.config.token)
                        .then(res => {
                            if (res.data.result_code !== "success") {
                                that.$notify({
                                    title: '警告',
                                    message: 'ctastrategy/param接口报错',
                                    type: 'warning',
                                    duration: 0,
                                });
                                return;
                            } else {
                                _strategy[name]['par'] = res.data.data;
                                that.strategy = _strategy;
                                that.loading.strategy = false;
                            }

                        })
                        .catch(res => {
                            that.$notify({
                                title: '警告',
                                message: 'ctastrategy/param接口报错',
                                type: 'warning',
                                duration: 0,
                            });
                        })
                },

                onLoadInfo(apiName, dataArr) {
                    const that = this;

                    if (this.config.token !== undefined) {
                        gInfo(apiName, this.config.token)
                    } else {
                        axios.get(host + '/token?username=test&password=test', {})
                            .then(function (res) {
                                if (res.status == 200 && res.data.result_code == "success") {
                                    let token = res.data.data
                                    gInfo(apiName, token)
                                } else {
                                    that.$notify({title: '警告', message: 'token获取失败', type: 'warning', duration: 0,});
                                }
                            })
                            .catch(function (res) {
                                that.$notify({title: '警告', message: 'token获取失败', type: 'warning', duration: 0,});
                            });
                    }

                    function gInfo(apiName, token) {
                        axios.get(host + "/" + apiName + "?token=" + token)
                            .then(res => {
                                if (res.data.result_code == "success") {
                                    if (apiName == "order") {
                                        res.data.data.forEach((item) => {
                                            item["_vtOrderID"] = item.vtOrderID.replace(/\./g, "")
                                            that.orderObj[item._vtOrderID] = item;
                                        })
                                        sorted_order_list = Object.keys(that.orderObj).sort(sortVtOrderID);
                                        for (i in sorted_order_list) {
                                            that.order.push(that.orderObj[sorted_order_list[i]]);
                                        }
                                    }
                                    else {
                                        that[dataArr] = that[dataArr].concat(res.data.data).reverse()
                                    }

                                } else {
                                    that.$notify({
                                        title: '警告',
                                        message: '服务异常，获取信息失败1',
                                        type: 'warning',
                                        duration: 3000,
                                    });
                                }
                            })
                            .catch(res => {
                                that.$notify({title: '警告', message: '服务异常，获取信息失败2', type: 'warning', duration: 3000,});
                            })
                    }
                },
                onSubmit(e) {

                    if (this.config.token == undefined || this.config.token == "") {
                        this.$alert('请先登录', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    if (this.config.gateway == undefined || this.config.gateway == "") {
                        this.$alert('请先连接CTP', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    if (this.form.vtSymbol == "") {
                        this.$alert('请填写代码！', '警告', {confirmButtonText: '确定',});
                        return;
                    }
                    if (this.form.lastPrice == "") {
                        this.$alert('请填写价格！', '警告', {confirmButtonText: '确定',});
                        return;
                    }
                    if (this.form.volume == "") {
                        this.$alert('请填写数量！', '警告', {confirmButtonText: '确定',});
                        return;
                    }
                    if (this.form.priceType == "") {
                        this.$alert('请选择价格类型！', '警告', {confirmButtonText: '确定',});
                        return;
                    }
                    if (this.form.direction == "") {
                        this.$alert('请选择方向类型！', '警告', {confirmButtonText: '确定',});
                        return;
                    }
                    if (this.form.offset == "") {
                        this.$alert('请选择开平！', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    this.loading.order = true;

                    const that = this;
                    axios.post(host + '/order', {
                        vtSymbol: this.form.vtSymbol,
                        price: this.form.lastPrice,
                        volume: this.form.volume,
                        priceType: this.form.priceType,
                        direction: this.form.direction,
                        offset: this.form.offset,
                        token: this.config.token,
                    })
                        .then(function (res) {
                            that.loading.order = false;
                            if (res.data.result_code == "success") {
                                that.$message({message: '发单成功', type: 'success'});
                            } else {
                                that.$notify({title: '警告', message: '服务异常，发单失败', type: 'warning', duration: 3000,});
                            }
                        })
                        .catch(function (err) {
                            that.loading.order = false;
                            that.$notify({title: '警告', message: '服务异常，发单失败', type: 'warning', duration: 3000,});
                        });
                },
                onSubscribe(target) {

                    if (this.config.token == undefined || this.config.token == "") {
                        this.$alert('请先登录', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    if (this.config.gateway == undefined || this.config.gateway == "") {
                        this.$alert('请先连接CTP', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    const that = this;
                    if (typeof(target) !== "object") {
                        var _vtSymbol = target
                    } else {
                        var _vtSymbol = this.form.vtSymbol
                    }
                    if (this.config.token == undefined || this.config.token == "") {
                        this.gToken()
                    }
                    if (_vtSymbol == undefined || _vtSymbol == "") {
                        return this.$alert('请输入代码', '提示', {
                            confirmButtonText: '确定',
                        });
                    } else {
                        this.loading.subScribe = true;
                        axios.post(host + "/tick", {
                            vtSymbol: _vtSymbol,
                            token: this.config.token
                        })
                            .then(res => {
                                that.loading.subScribe = false;
                                if (res.data.result_code == "success") {
                                    let target = _vtSymbol
                                    that.clickTick(target)
                                    that.form.vtSymbol = target;
                                    that.$message({message: '订阅成功', type: 'success'});
                                } else {
                                    that.$notify({title: '警告', message: '订阅失败', type: 'warning', duration: 3000,});
                                }
                            })
                            .catch(res => {
                                that.loading.subScribe = false;
                                that.$notify({title: '警告', message: '服务异常，订阅失败', type: 'warning', duration: 3000,});
                            })
                    }
                },
                dOrder(e) {

                    if (this.config.token == undefined || this.config.token == "") {
                        this.$alert('请先登录', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    if (this.config.gateway == undefined || this.config.gateway == "") {
                        this.$alert('请先连接CTP', '警告', {confirmButtonText: '确定',});
                        return;
                    }
                    console.log(e.vtOrderID);
                    let vtOrderID = e.vtOrderID,
                        that = this;
                    axios.delete(host + "/order?vtOrderID=" + vtOrderID + "&token=" + this.config.token)
                        .then(res => {
                            if (res.data.result_code == "success") {
                                that.$message({message: '撤单已提交', type: 'success'});
                            } else {
                                that.$notify({title: '警告', message: '服务异常，撤单提交失败', type: 'warning', duration: 2000,});
                            }
                        })
                        .catch(res => {
                            that.$notify({title: '警告', message: '服务异常，撤单提交失败', type: 'warning', duration: 2000,});
                        })
                },
                dAllOrder(e) {

                    if (this.config.token == undefined || this.config.token == "") {
                        this.$alert('请先登录', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    if (this.config.gateway == undefined || this.config.gateway == "") {
                        this.$alert('请先连接CTP', '警告', {confirmButtonText: '确定',});
                        return;
                    }
                    console.log(e.vtOrderID);
                    let vtOrderID = "",
                        that = this;
                    axios.delete(host + "/order?vtOrderID=" + vtOrderID + "&token=" + this.config.token)
                        .then(res => {
                            if (res.data.result_code == "success") {
                                that.$message({message: '撤单已提交', type: 'success'});
                            } else {
                                that.$notify({title: '警告', message: '服务异常，撤单提交失败', type: 'warning', duration: 2000,});
                            }
                        })
                        .catch(res => {
                            that.$notify({title: '警告', message: '服务异常，撤单提交失败', type: 'warning', duration: 2000,});
                        })
                },
                handleClick(row) {
                    this.onSubscribe(row.vtSymbol)
                },
                handleTab(tab) {
                    const that = this;
                    that.loading.contract = true;
                    if (tab.name == "search") {
                        this.gContract()
                    } else if (tab.name == "cta") {
                        this.judgeIfStrategy()
                        this.gCtaLog()
                    }
                },
                judgeIfStrategy() {

                    if (this.config.token == undefined || this.config.token == "") {
                        this.$alert('请先登录', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    if (this.config.gateway == undefined || this.config.gateway == "") {
                        this.$alert('请先连接CTP', '警告', {confirmButtonText: '确定',});
                        return;
                    }

                    let that = this;
                    axios.get(host + "/ctastrategy/name?token=" + this.config.token)
                        .then(res => {
                            let nameArray = res.data.data;
                            nameArray.forEach(function (item) {
                                _strategy[item] = {name: item};
                                that.gParams(item)
                                that.gVar(item)
                            })
                        })
                        .catch(res => {
                            that.$notify({title: '警告', message: '连接异常', type: 'warning', duration: 4500,});
                        })
                },
                gContract() {
                    const that = this;
                    if (that.contract.length == 0) {
                        axios.get(host + "/contract?token=" + this.config.token)
                            .then(res => {
                                that.loading.contract = false;
                                if (res.data.result_code == "success") {
                                    that.contract = res.data.data
                                } else {
                                    that.$notify({title: '警告', message: '连接异常', type: 'warning', duration: 4500,});
                                }
                            })
                            .catch(res => {
                                that.$notify({title: '警告', message: '连接异常', type: 'warning', duration: 4500,});
                            })
                    }

                },
                gGateway() {
                    const that = this;
                    axios.post(host + '/gateway', {
                        token: 'MjAxOC0xMS0wNXRlc3Q=',
                        gatewayName: 'CTP'
                    })
                        .then(function (res) {
                            that.config.gateway = true;
                            that.$message({message: '已连接CTP', type: 'success'});
                        })
                        .catch(function (err) {
                            console.log("res", err)
                        });
                },
                handleTabLeft(tab, event) {
                },
                handleTabRight(tab, event) {
                },
            }
        })
    </script>
{% endblock %}
